package common;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.hp.hpl.jena.ontology.*;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;

public class SkillManSchema 
{
	public static String myNS="http://www.unisa.it/skill_management.owl#";
	public static String cvNS="http://kaste.lv/~captsolo/semweb/resume/cv.rdfs#";
	//private static String wnNS="http://xmlns.com/wordnet/1.6/";
	//private static String foafNS="http://xmlns.com/foaf/0.1/";
	//private static String nothing="http://www.w3.org/2002/07/owl#Nothing";
	private OntModel onto;
	private SkillManTaxonomy tax;
	private String schema="skill_management.owl";
	private String cwd="";
	
	public SkillManSchema()
	{
		onto = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RDFS_INF, null );
	}
	
	public void load()
	{
		onto.read("file:"+cwd+schema, "" );
		
		OntClass cl=onto.getOntClass(cvNS+"Skill");
		tax=new SkillManTaxonomy(cl);
	}
	
	public SkillManTaxonomy getTaxonomy()
	{
		return tax;
	}
	
	public boolean addSkill( String parent, String child, String comment )
	{
		OntClass p=onto.getOntClass(myNS+parent);
		
		if(p==null)
		{
			System.out.println("Invalid parent class: "+p);
			return false;
		}
		
		OntClass c=onto.createClass(myNS+child);
		
		if(c==null)
		{
			System.out.println("Cannot create class: "+c);
			return false;
		}
		
		c.addComment(comment, null);
		c.addSuperClass(p);
		
		return true;
	}

	public boolean existsSkill(OntClass parent) 
	{
		ExtendedIterator it=onto.getOntClass(cvNS+"Skill").listSubClasses(false);
		while( it.hasNext() )
		{
			OntClass cl=(OntClass)it.next();
			if( cl.hasSubClass( parent ) )
				return true; 
		}
		return false;
	}

	public void store() throws FileNotFoundException 
	{		
		FileOutputStream fp=new FileOutputStream( new File(cwd+schema) );
		onto.write(fp);
	}
	
	public boolean setCWD(String dir)
	{
		if( !dir.equals("") && dir.charAt( dir.length()-1 )!='/' )
			dir+="/";
		
		File fp=new File(dir+".");
		if( !fp.exists() || !fp.canWrite() )
		{
			System.out.println("WARN: Unreadable CWD. Using default.");
			return false;
		}
		
		System.out.println("CWD: "+dir);
		cwd=dir;
		return true;
	}
}
